package org.jbch.shittim;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TabWidget;

public class Utils {

	static final String URL = "http://rss.jbch.org/boards/4_4_45.xml";
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_MP3 = "mp3";
    static final String KEY_WRITER = "writer";
    static final String KEY_PUBDATE = "pubDate";
    static final String KEY_DESC = "description";
    
	static int sActivSeekBarIndex=-1;
    static int sActiveTabIndex = -1;
	static final int MENU1 = Menu.FIRST + 0;		// 새로고침
	static final int MENU2 = Menu.FIRST + 1;		// 환경설정
	private static String LOG_TAG="jbchLog";
	

//	public static ArrayList<HashMap<String, String>> pList= new ArrayList<HashMap<String, String>>();

	public static BackgroundAudioService sService;
    private static HashMap<Context, ServiceBinder> sConnectionMap = new HashMap<Context, ServiceBinder>();

    public static class ServiceToken {
        ContextWrapper mWrappedContext;
        ServiceToken(ContextWrapper context) {
            mWrappedContext = context;
        }
    }

    public static ServiceToken bindToService(Activity context, ServiceConnection callback) {
        Activity realActivity = context.getParent();
        if (realActivity == null) {
            realActivity = context;
        }
        ContextWrapper cw = new ContextWrapper(realActivity);
        cw.startService(new Intent(cw, BackgroundAudioService.class));	//BackgroundAudioService 의 onStartCommand(Intent, int, int) 호출
        ServiceBinder sb = new ServiceBinder(callback);
        if (cw.bindService((new Intent()).setClass(cw, BackgroundAudioService.class), sb, 0)) {
            sConnectionMap.put(cw, sb);
            return new ServiceToken(cw);
        }
        Log.e("Music", "Failed to bind to service");
        return null;
    }

    public static void unbindFromService(ServiceToken token) {
        if (token == null) {
            Log.e("MusicUtils", "Trying to unbind with null token");
            return;
        }
        ContextWrapper cw = token.mWrappedContext;
        ServiceBinder sb = sConnectionMap.remove(cw);
        if (sb == null) {
            Log.e("MusicUtils", "Trying to unbind for unknown Context");
            return;
        }
        cw.unbindService(sb);
        if (sConnectionMap.isEmpty()) {
            // presumably there is nobody interested in the service at this point,
            // so don't hang on to the ServiceConnection
            sService = null;
        }
    }
    

    private static class ServiceBinder implements ServiceConnection {
        ServiceConnection mCallback;
        ServiceBinder(ServiceConnection callback) {
            mCallback = callback;
        }
        
        public void onServiceConnected(ComponentName className, android.os.IBinder service) {
            sService =  ((BackgroundAudioService.BackgroundAudioServiceBinder) service).getService();
            if (mCallback != null) {
                mCallback.onServiceConnected(className, service);
            }
        }
        
        public void onServiceDisconnected(ComponentName className) {
            if (mCallback != null) {
                mCallback.onServiceDisconnected(className);
            }
            sService = null;
        }
        
    }
    
    
//    public static ArrayList<HashMap<String, String>> getPlayList(){
//    	try {
////    		Log.e(LOG_TAG , "sService.playList() 크기:"+sService.playList().size());
//			return sService.playList();
//		} catch (RemoteException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return null;
//    }
    
    public static List<ShittimInfo> getPlayList(){
    	try {
			return sService.playList();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return null;
    }
    
    
    
    public static boolean getWasPlaying(){
    	return sService.isWasPlaying();
    	
    }
    
    static void updateNetworkState(Activity a , int resId, int state) {

		View viewActivity = a.findViewById(resId);
    	
    }
    

	static void updateNowPlaying(Activity a) {
		View nowPlayingView = a.findViewById(R.id.nowplayingBar);
		if (nowPlayingView == null) {
			return;
		}
		boolean withtabs = false;
		Intent intent = a.getIntent();
		if (intent != null) {
			withtabs = intent.getBooleanExtra("withtabs", false);
		}
		// if (true && Utils.sService != null &&
		// MusicUtils.sService.getAudioId() != -1) {
		if (true && Utils.sService != null) {
			// TextView title = (TextView)
			// nowPlayingView.findViewById(R.id.title);
			// TextView artist = (TextView)   
			// nowPlayingView.findViewById(R.id.artist);
			// title.setText(MusicUtils.sService.getTrackName());
			// String artistName = MusicUtils.sService.getArtistName();
			// if (MediaStore.UNKNOWN_STRING.equals(artistName)) {
			// artistName = a.getString(R.string.unknown_artist_name);
			// }
			// artist.setText(artistName);
			nowPlayingView.setVisibility(View.VISIBLE);
			nowPlayingView.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					Context c = v.getContext();
					c.startActivity(new Intent(c, thirdActivity.class));
				}
			});
			return;
		}
		nowPlayingView.setVisibility(View.GONE);
	}

	static void updateBottomSeekBar(Activity a , boolean withseekbar){
		
		final SeekBar sb = (SeekBar)a.findViewById(R.id.bottomSeekbar);
		if(withseekbar){
			sb.setVisibility(View.VISIBLE);
			sActivSeekBarIndex=1;
		}else{
			sb.setVisibility(View.GONE);
			sActivSeekBarIndex=-1;
			
		}

		 setIntPref(a, "activeseekbar", sActivSeekBarIndex);
		
	}
	
	static void setPlayBtnState(Activity a, int state , int resId){

//		final ImageButton playBtn = (ImageButton)a.findViewById(R.id.playBtn);
		final ImageButton playBtn = (ImageButton)a.findViewById(resId);

		if(state==0){
			playBtn.setImageResource(R.drawable.cur_play);	// setText("▷");
		}else if(state==1){
			playBtn.setImageResource(R.drawable.cur_pause);
//			playBtn.setText("∥");
		}
		
	}

    static boolean updateButtonBar(Activity a, int highlight) {
        final TabWidget ll = (TabWidget) a.findViewById(R.id.buttonbar);
        boolean withtabs = false;
        Intent intent = a.getIntent();
        if (intent != null) {
            withtabs = intent.getBooleanExtra("withtabs", false);
        }
        
        if (highlight == 0 || !withtabs) {
            ll.setVisibility(View.GONE);
            return withtabs;
        } else if (withtabs) {
            ll.setVisibility(View.VISIBLE);
        }
        for (int i = ll.getChildCount() - 1; i >= 0; i--) {
            
            View v = ll.getChildAt(i);
            boolean isActive = (v.getId() == highlight);
            if (isActive) {
                ll.setCurrentTab(i);
                sActiveTabIndex = i;
            }
            v.setTag(i);
			v.setOnFocusChangeListener(new View.OnFocusChangeListener() {

				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) {
						for (int i = 0; i < ll.getTabCount(); i++) {
							if (ll.getChildTabViewAt(i) == v) {
								ll.setCurrentTab(i);
								processTabClick((Activity) ll.getContext(), v,ll.getChildAt(sActiveTabIndex).getId());
								break;
							}
						}
					}
				}
			});

			v.setOnClickListener(new View.OnClickListener() {

				public void onClick(View v) {
					processTabClick((Activity) ll.getContext(), v, ll.getChildAt(sActiveTabIndex).getId());
				}
			});
        }
        return withtabs;
    }
    

    static void processTabClick(Activity a, View v, int current) {
        int id = v.getId();
        if (id == current) {
            return;
        }

        final TabWidget ll = (TabWidget) a.findViewById(R.id.buttonbar);

		activateTab(a, id);
		// if (id != R.id.nowplayingtab) {
		ll.setCurrentTab((Integer) v.getTag());
		 setIntPref(a, "activetab", id);
		// }
    }

    static int getIntPref(Context context, String name, int def) {
        SharedPreferences prefs =
            context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
        return prefs.getInt(name, def);
    }

    static void setIntPref(Context context, String name, int value) {
        SharedPreferences prefs =
            context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
        Editor ed = prefs.edit();
        ed.putInt(name, value);
        SharedPreferencesCompat.apply(ed);
    }

	static void activateTab(Activity a, int id) {

        Intent intent = new Intent(Intent.ACTION_PICK);

        switch (id) {
	        case R.id.tab01:
	            intent.setDataAndType(Uri.EMPTY, "org.jbch.shittah.broad/tab01");
	            break;
	        case R.id.tab02:
	            intent.setDataAndType(Uri.EMPTY, "org.jbch.shittah.broad/tab02");
	            break;

	        case R.id.tab03:
	            intent.setDataAndType(Uri.EMPTY, "org.jbch.shittah.broad/tab03");
	            break;

	        case R.id.tab04:
	            intent.setDataAndType(Uri.EMPTY, "org.jbch.shittah.broad/tab04");
	            break; 
	            
//            case R.id.albumtab:
//                intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/album");
//                break;
//            case R.id.songtab:
//                intent.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track");
//                break;
//            case R.id.playlisttab:
//                intent.setDataAndType(Uri.EMPTY, MediaStore.Audio.Playlists.CONTENT_TYPE);
//                break;
//            case R.id.nowplayingtab:
//                intent = new Intent(a, MediaPlaybackActivity.class);
//                a.startActivity(intent);
//                // fall through and return  
            default:
                return;
        }

        intent.putExtra("withtabs", true);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		a.startActivity(intent);
        a.finish();
        a.overridePendingTransition(0, 0);  // 사라질때 애니메이션 처리
        
	}
	
	static String getAudioPlayTime(int progress){
		
		int m=progress/60000;
		
		String min = ("0"+m);
		min = min.substring(min.length() - 2, min.length());
		
		int s=(progress%60000)/1000;

		String sec = ("0"+s);
		sec = sec.substring(sec.length() - 2, sec.length());
		
		
		return min+":"+sec;
	}

}
